package com.boolib.http.sign.spi;


import com.boolib.http.core.abstracts.AbstractRequestHandler;
import com.boolib.http.core.exception.ExceptionFactory;
import com.boolib.http.core.util.AssertUtil;
import com.boolib.http.sign.model.MessageBody;
import com.boolib.http.sign.util.SignUtil;
import com.boolib.http.sign.wrapper.DecryptBodyRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author wfq
 */
@Slf4j
@Component
public class DecryptBodyRequestHandler extends AbstractRequestHandler {


    @Override
    public boolean isSupport() {
        return !("get".equalsIgnoreCase(httpServletRequest.getMethod()) || httpServletRequest.getContextPath().contains("internal") || "application/form-data".equalsIgnoreCase(httpServletRequest.getContentType()));
    }

    @Override
    public void handler(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        DecryptBodyRequestWrapper decryptBodyRequestWrapper = null;
        try {
            decryptBodyRequestWrapper = new DecryptBodyRequestWrapper(httpServletRequest);
            MessageBody messageBody = decryptBodyRequestWrapper.getMessageBody();
            String data = messageBody.getData();
            String sign = messageBody.getSign();
            AssertUtil.trueOrThrow(SignUtil.verifySign(data,sign), ExceptionFactory.ofCheck("E10000","签名失败"));
            byte[] decode = Base64Utils.decode(data.getBytes());
            log.info("body: {}",new String(decode));
            decryptBodyRequestWrapper.refreshData(decode);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.httpServletRequest = decryptBodyRequestWrapper;
        this.httpServletResponse = httpServletResponse;

    }


}
